package trading_strategy.strategies;

import org.apache.log4j.Logger;
import trading_strategy.Strategy;
import trading_strategy.events.*;
import trading_strategy.instruments.ListedInstrument;
import trading_strategy.orders.Order;
import trading_strategy.orders.SingleOrderAutomaton;
import trading_strategy.positions.InstrumentPosition;
import trading_strategy.positions.Trade;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 24 mai 2010
 * Time: 16:26:16
 * To change this template use File | Settings | File Templates.
 */
public class TradeMomentumStrategy extends Strategy implements SingleOrderAutomaton.OrderProvider, TriggerPositionEnterer.PositionEntererListener {
    private int intervalSecs = 30;

    class TradeSignal extends AbstractMarketEvent {
        Direction direction;
        double entryLevel;
        double exitLevel;
        long maxTsValidity;

        TradeSignal(long ts, Direction direction, double entryLevel, double exitLevel, long maxTsValidity) {
            super(ts);
            this.direction = direction;
            this.entryLevel = entryLevel;
            this.exitLevel = exitLevel;
            this.maxTsValidity = maxTsValidity;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(direction);
            sb.append(" at ").append(sdf.format(getDate()));
            return sb.toString();
        }
    }


    public static final Logger LOGGER = Logger.getLogger(TradeMomentumStrategy.class);
    SingleOrderAutomaton automaton;
    private TargetPositionExiter positionExiter;
    private TargetPositionEnterer positionEnterer;
    private int eventCounter = 0;
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
    private Date date = this.date;
    private OrderBookUpdate lastOrderBookUpdate;

    private InstrumentPosition position;

    enum State {
        PASSIVE, SIGNAL_DETECTED, IN_POSITION
    }

    ListedInstrument instrument;
    LinkedList<TradeSignal> tradeEvents = new LinkedList<TradeSignal>();
    LinkedList<PublicTradeUpdate> buyTrades = new LinkedList<PublicTradeUpdate>();
    LinkedList<PublicTradeUpdate> sellTrades = new LinkedList<PublicTradeUpdate>();

    @Override
    public double getPnL() {
        return position.getPnL();
    }

    State state = State.PASSIVE;


    public TradeMomentumStrategy(Date date, ListedInstrument instrument) {
        this.date = date;
        this.instrument = instrument;
        this.automaton = new SingleOrderAutomaton(instrument, this);
        this.position = new InstrumentPosition(instrument);
    }

    @Override
    public void onMarketEvent(AbstractMarketEvent event) {
        if (event instanceof MarketEvent) {
            if (((MarketEvent) event).getState() == MarketEvent.MarketState.CLOSED) {
                stop();
            }
            if (((MarketEvent) event).getState() == MarketEvent.MarketState.OPEN) {
                start();
            }
        }
        if (!isStarted()) {
            return;
        }
        if (event instanceof PublicTradeUpdate) {
            PublicTradeUpdate ptu = (PublicTradeUpdate) event;
            if (ptu.getSide() == PublicTradeUpdate.TradeSide.BUY) {
                buyTrades.push(ptu);
            } else if (ptu.getSide() == PublicTradeUpdate.TradeSide.SELL) {
                sellTrades.push(ptu);
            }

            TradeStats resBuy = getQtyInTimeInterval(event, buyTrades);
            int buyTradeQty = resBuy.qtyTraded;
            TradeStats resSell = getQtyInTimeInterval(event, sellTrades);
            int sellTradeQty = resSell.qtyTraded;

            if (ptu.getSide() == PublicTradeUpdate.TradeSide.BUY && buyTradeQty > 4 * sellTradeQty && buyTradeQty > 50) {
                if (resBuy.nbTrades >= resSell.nbTrades * 2) {
                    // Buy signal
                    double targetPrice = Math.min(lastOrderBookUpdate.getBook().getBid(0), resBuy.avgPrice) + instrument.getTick();
                    double deactivatingPrice = targetPrice - 2;
                    getEventDispatcher().addScheduledEvent(new TradeSignal(event.getTs(), Direction.BUY, targetPrice, deactivatingPrice, event.getTs() + 100000000l));
                }
            }
            if (ptu.getSide() == PublicTradeUpdate.TradeSide.SELL && sellTradeQty > 4 * buyTradeQty && sellTradeQty > 50) {
                if (resBuy.nbTrades >= resSell.nbTrades * 2) {
                    // Sell signal
                    double targetPrice = Math.max(lastOrderBookUpdate.getBook().getAsk(0), resSell.avgPrice) - instrument.getTick();
                    double deactivatingPrice = targetPrice + 2;
                    getEventDispatcher().addScheduledEvent(new TradeSignal(event.getTs(), Direction.SELL, targetPrice, deactivatingPrice, event.getTs() + 100000000l));
                }
            }
        }

        if (event instanceof OrderBookUpdate)

        {
            OrderBookUpdate odu = (OrderBookUpdate) event;
            lastOrderBookUpdate = odu;
        }

        if (event instanceof TradeSignal)

        {
            TradeSignal signal = (TradeSignal) event;
            tradeEvents.add(signal);
            if (state == State.PASSIVE) {
                if (lastOrderBookUpdate != null) {
                    state = State.SIGNAL_DETECTED;
                    LOGGER.debug("New signal " + signal);
                    positionEnterer = new TargetPositionEnterer(this, instrument, signal.direction, signal.entryLevel, signal.exitLevel, signal.maxTsValidity, automaton);
                }
            } else if (state == State.SIGNAL_DETECTED) {
                if (positionEnterer.getDirection() != signal.direction) {
                    // Opposite signal
                    positionEnterer.deactivated(event.getTs());
                    state = State.PASSIVE;
                }
            } else if (state == State.IN_POSITION) {
                // We are currently in position - it may be a signal to close the position
                if (positionExiter != null && positionExiter.direction == signal.direction) {
                    LOGGER.info("Close position - inverse signal detected");
                    positionExiter.hit(event.getTs());
                }
            }
        }

    }

    class TradeStats {
        int qtyTraded;
        int nbTrades;
        double avgPrice;
    }
    private TradeStats getQtyInTimeInterval(AbstractMarketEvent event, LinkedList<PublicTradeUpdate> list) {
        int buyTradeQty = 0;
        Iterator<PublicTradeUpdate> iterator = list.iterator();
        TradeStats stats = new TradeStats();
        for (; iterator.hasNext();) {
            PublicTradeUpdate tradeUpdate = iterator.next();
            if (event.getTs() - tradeUpdate.getTs() > intervalSecs * 1000000l) {
                iterator.remove();
                break;
            } else {
                stats.qtyTraded += tradeUpdate.getQty();
                stats.nbTrades++;
                stats.avgPrice += tradeUpdate.getPrice() * tradeUpdate.getQty();
            }
        }
        for (; iterator.hasNext();) {
            PublicTradeUpdate tradeUpdate = iterator.next();
            iterator.remove();
        }
        stats.avgPrice /= (double) stats.qtyTraded;
        return stats;
    }

    @Override
    public boolean shouldStillSendOrder(Order order) {
        return true;
    }

    @Override
    public void onExecution(int qty, double price, Order order) {
        Trade trade = new Trade(order.getMatchingTimestamp(), date, qty, price, getClass().getName());
        position.addTrade(trade);
        if (state == State.SIGNAL_DETECTED) {
            if (positionEnterer != null) {
                positionEnterer.deactivated(order.getMatchingTimestamp());
                LOGGER.info("Position entered " + qty + "@" + price + " at " + sdf.format(new Date(order.getMatchingTimestamp() / 1000)));
                positionEnterer = null;
                long mustExitBefore = order.getMatchingTimestamp() + 3 * intervalSecs * 1000000l;
                long mustConfirmBefore = order.getMatchingTimestamp() + intervalSecs * 1000000l;
                positionExiter = new TargetPositionExiter(instrument, this, automaton, trade, 4, 2.5, 0.5, mustExitBefore, 0.5, mustConfirmBefore, null);
                state = State.IN_POSITION;
            }
        } else if (state == State.IN_POSITION) {
            if (positionExiter != null) {
                positionExiter.deactivated(order.getMatchingTimestamp());
                LOGGER.info("Position exited " + qty + "@" + price + " at " + sdf.format(new Date(order.getMatchingTimestamp() / 1000)));
                positionExiter = null;
                state = State.PASSIVE;
            }
        }
        dumpGraph();
    }

    public void register() {
        // Make sure that we subscribe to AMM before candle, in order to get the AMM before the candle...
        EventManager.getInstance().subscribe(getListener(), instrument.getTradeEventProvider());
        EventManager.getInstance().subscribe(getListener(), instrument.getOrderBookProvider());
        EventManager.getInstance().subscribe(getListener(), instrument.getMarket().getMarketEventProvider());
    }

    public int getEventCounter() {
        return eventCounter;
    }

    @Override
    public void deactivated() {
        if (state == State.SIGNAL_DETECTED) {
            state = State.PASSIVE;
        }
    }

    @Override
    public void stop() {
        if (state == State.IN_POSITION) {
            positionExiter.hit(lastOrderBookUpdate.getTs(), "Stopping strategy");
        }
        super.stop();
    }

    public void dumpGraph() {
    }

}